
<!DOCTYPE html>
<html lang="">


<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
  <meta name="theme-color" content="#202020">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <script src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" async></script>
  
  
    <meta name="keywords" content>
  

  
    <meta name="description" content="第二十三章 Django cookie 与 session">
  
  
  
  <link rel="icon" type="image/x-icon" href="/images/footer-logo.png">
  
  <title>第二十三章 Django cookie 与 session [ 51AIOps 专注于运维自动化  微信： kaipython ]</title>
  
    <!-- stylesheets list from config.yml -->
    
      <link rel="stylesheet" href="//cdn.bootcss.com/pure/1.0.0/pure-min.css">
    
      <link rel="stylesheet" href="/css/xoxo.css">
    
  
</head>


<body>
  <div class="nav-container">
    <nav class="home-menu pure-menu pure-menu-horizontal">
  <a class="pure-menu-heading" href="/">
    
    <span class="title" style="text-transform:none">51AIOps 专注于运维自动化  微信： kaipython</span>
  </a>

  <ul class="pure-menu-list clearfix">
      
          
            
              <li class="pure-menu-item"><a href="/" class="pure-menu-link">首页</a></li>
            
          
      
  </ul>
   
</nav>

  </div>

  <div class="container" id="content-outer">
    <div class="inner" id="content-inner" style='margin-left:-68px!important'>
      <div class="post-container">
  <article class="post" id="post">
    <header class="post-header text-center">
      <h1 class="title">
        第二十三章 Django cookie 与 session
      </h1>
      <span>
        
        <time class="time" datetime="2019-11-08T16:00:00.000Z">
        2019-11-09
      </time>
        
      </span>
      <span class="slash">/</span>
      <span class="post-meta">
      <span class="post-tags">
        
      </span>
    </span>
      <span class="slash">/</span>
      <span class="read">
      <span id="busuanzi_value_page_pv"></span> 点击
    </span>
      <span class="slash">/</span>
    </header>

    <div class="post-content">
      <h3 id="Django-cookie-与-session"><a href="#Django-cookie-与-session" class="headerlink" title="Django cookie 与 session"></a>Django cookie 与 session</h3><p>Cookie 是存储在客户端计算机上的文本文件，并保留了各种跟踪信息。</p>
<p>识别返回用户包括三个步骤：</p>
<ul>
<li>服务器脚本向浏览器发送一组 Cookie。例如：姓名、年龄或识别号码等。</li>
<li>浏览器将这些信息存储在本地计算机上，以备将来使用。</li>
<li>当下一次浏览器向 Web 服务器发送任何请求时，浏览器会把这些 Cookie 信息发送到服务器，服务器将使用这些信息来识别用户。</li>
</ul>
<p>HTTP 是一种”无状态”协议，这意味着每次客户端检索网页时，客户端打开一个单独的连接到 Web 服务器，服务器会自动不保留之前客户端请求的任何记录。</p>
<p>但是仍然有以下三种方式来维持 Web 客户端和 Web 服务器之间的 session 会话：</p>
<h4 id="Cookies"><a href="#Cookies" class="headerlink" title="Cookies"></a>Cookies</h4><p>一个 Web 服务器可以分配一个唯一的 session 会话 ID 作为每个 Web 客户端的 cookie，对于客户端的后续请求可以使用接收到的 cookie 来识别。</p>
<p>在Web开发中，使用 session 来完成会话跟踪，session 底层依赖 Cookie 技术。</p>
<p><img src="https://www.runoob.com/wp-content/uploads/2020/05/cookie.png" alt="img"></p>
<h4 id="Django-中-Cookie-的语法"><a href="#Django-中-Cookie-的语法" class="headerlink" title="Django 中 Cookie 的语法"></a>Django 中 Cookie 的语法</h4><p>设置 cookie:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">rep.set_cookie(key,value,...) </span><br><span class="line">rep.set_signed_cookie(key,value,salt=&apos;加密盐&apos;,...)</span><br></pre></td></tr></table></figure>

<p>获取 cookie:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">request.COOKIES.get(key)</span><br></pre></td></tr></table></figure>

<p>删除 cookie:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">rep =HttpResponse || render || redirect </span><br><span class="line">rep.delete_cookie(key)</span><br></pre></td></tr></table></figure>

<p><img src="https://www.runoob.com/wp-content/uploads/2020/05/Django-cs_2.png" alt="img"></p>
<p><img src="https://www.runoob.com/wp-content/uploads/2020/05/Django-cs_3.png" alt="img"></p>
<h4 id="创建应用和模型"><a href="#创建应用和模型" class="headerlink" title="创建应用和模型"></a>创建应用和模型</h4><p><code>models.py</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span>  <span class="title">UserInfo</span><span class="params">(models.Model)</span>:</span></span><br><span class="line">  username = models.CharField(max_length=<span class="number">32</span>)</span><br><span class="line">  password = models.CharField(max_length=<span class="number">64</span>)</span><br></pre></td></tr></table></figure>

<p><img src="https://www.runoob.com/wp-content/uploads/2020/05/Django-cs_4.png" alt="img"></p>
<p><code>Urls.py</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.contrib <span class="keyword">import</span> admin</span><br><span class="line"><span class="keyword">from</span> django.urls <span class="keyword">import</span> path</span><br><span class="line"><span class="keyword">from</span> cookie <span class="keyword">import</span> views</span><br><span class="line">urlpatterns = [</span><br><span class="line">  path(<span class="string">'admin/'</span>, admin.site.urls),</span><br><span class="line">  path(<span class="string">'login/'</span>, views.login),</span><br><span class="line">  path(<span class="string">'index/'</span>, views.index),</span><br><span class="line">  path(<span class="string">'logout/'</span>, views.logout),</span><br><span class="line">  path(<span class="string">'order/'</span>, views.logout)</span><br></pre></td></tr></table></figure>

<p><img src="https://www.runoob.com/wp-content/uploads/2020/05/Django-cs_5.png" alt="img"></p>
<p><code>Views.py</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">login</span><span class="params">(request)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> request.method == <span class="string">"GET"</span>:</span><br><span class="line">        <span class="keyword">return</span> render(request, <span class="string">"login.html"</span>)</span><br><span class="line">    username = request.POST.get(<span class="string">"username"</span>)</span><br><span class="line">    password = request.POST.get(<span class="string">"pwd"</span>)</span><br><span class="line"></span><br><span class="line">    user_obj = models.UserInfo.objects.filter(username=username, password=password).first()</span><br><span class="line">    print(user_obj.username)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> user_obj:</span><br><span class="line">        <span class="keyword">return</span> redirect(<span class="string">"/login/"</span>)</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        rep = redirect(<span class="string">"/index/"</span>)</span><br><span class="line">        rep.set_cookie(<span class="string">"is_login"</span>, <span class="literal">True</span>)</span><br><span class="line">        <span class="keyword">return</span> rep</span><br><span class="line">        </span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">index</span><span class="params">(request)</span>:</span></span><br><span class="line">    print(request.COOKIES.get(<span class="string">'is_login'</span>))</span><br><span class="line">    status = request.COOKIES.get(<span class="string">'is_login'</span>) <span class="comment"># 收到浏览器的再次请求,判断浏览器携带的cookie是不是登录成功的时候响应的 cookie</span></span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> status:</span><br><span class="line">        <span class="keyword">return</span> redirect(<span class="string">'/login/'</span>)</span><br><span class="line">    <span class="keyword">return</span> render(request, <span class="string">"index.html"</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">logout</span><span class="params">(request)</span>:</span></span><br><span class="line">    rep = redirect(<span class="string">'/login/'</span>)</span><br><span class="line">    rep.delete_cookie(<span class="string">"is_login"</span>)</span><br><span class="line">    <span class="keyword">return</span> rep <span class="comment"># 点击注销后执行,删除cookie,不再保存用户状态，并弹到登录页面</span></span><br><span class="line">    </span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">order</span><span class="params">(request)</span>:</span></span><br><span class="line">    print(request.COOKIES.get(<span class="string">'is_login'</span>))</span><br><span class="line">    status = request.COOKIES.get(<span class="string">'is_login'</span>)</span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> status:</span><br><span class="line">        <span class="keyword">return</span> redirect(<span class="string">'/login/'</span>)</span><br><span class="line">    <span class="keyword">return</span> render(request, <span class="string">"order.html"</span>)</span><br></pre></td></tr></table></figure>

<p>以下创建三个模板文件：login.html、index.html、order.html。</p>
<p><code>Login.html</code></p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE html&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">"en"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"UTF-8"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Title<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"> </span><br><span class="line"><span class="tag">&lt;<span class="name">h3</span>&gt;</span>用户登录<span class="tag">&lt;/<span class="name">h3</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">form</span> <span class="attr">action</span>=<span class="string">""</span> <span class="attr">method</span>=<span class="string">"post"</span>&gt;</span></span><br><span class="line">    &#123;% csrf_token %&#125;</span><br><span class="line">    <span class="tag">&lt;<span class="name">p</span>&gt;</span>用户名： <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"text"</span> <span class="attr">name</span>=<span class="string">"username"</span>&gt;</span><span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">p</span>&gt;</span>密码： <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"password"</span> <span class="attr">name</span>=<span class="string">"pwd"</span>&gt;</span><span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"submit"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">form</span>&gt;</span></span><br><span class="line"> </span><br><span class="line"> </span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><code>Index.html</code></p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE html&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">"en"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"UTF-8"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Title<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"> </span><br><span class="line"> </span><br><span class="line"><span class="tag">&lt;<span class="name">h2</span>&gt;</span>index 页面。。。<span class="tag">&lt;/<span class="name">h2</span>&gt;</span></span><br><span class="line"> </span><br><span class="line"> </span><br><span class="line"><span class="tag">&lt;<span class="name">a</span> <span class="attr">href</span>=<span class="string">"/logout/"</span>&gt;</span>注销<span class="tag">&lt;/<span class="name">a</span>&gt;</span></span><br><span class="line"> </span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><code>Order.html</code></p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE html&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">"en"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"UTF-8"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Title<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"> </span><br><span class="line"> </span><br><span class="line"><span class="tag">&lt;<span class="name">h2</span>&gt;</span>order 页面。。。<span class="tag">&lt;/<span class="name">h2</span>&gt;</span></span><br><span class="line"> </span><br><span class="line"> </span><br><span class="line"><span class="tag">&lt;<span class="name">a</span> <span class="attr">href</span>=<span class="string">"/logout/"</span>&gt;</span>注销<span class="tag">&lt;/<span class="name">a</span>&gt;</span></span><br><span class="line"> </span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="Session-保存在服务端的键值对"><a href="#Session-保存在服务端的键值对" class="headerlink" title="Session(保存在服务端的键值对)"></a>Session(保存在服务端的键值对)</h4><p>服务器在运行时可以为每一个用户的浏览器创建一个其独享的 session 对象，由于 session 为用户浏览器独享，所以用户在访问服务器的 web 资源时，可以把各自的数据放在各自的 session 中，当用户再去访问该服务器中的其它 web 资源时，其它 web 资源再从用户各自的 session 中取出数据为用户服务。</p>
<p><img src="https://www.runoob.com/wp-content/uploads/2020/05/5-21-1.jpg" alt="img"></p>
<h5 id="工作原理"><a href="#工作原理" class="headerlink" title="工作原理"></a>工作原理</h5><ul>
<li><p>a. 浏览器第一次请求获取登录页面 login。</p>
</li>
<li><p>b. 浏览器输入账号密码第二次请求，若输入正确，服务器响应浏览器一个 index 页面和一个键为 sessionid，值为随机字符串的 cookie，即 set_cookie (“sessionid”,随机字符串)。</p>
</li>
<li><p>c. 服务器内部在 django.session 表中记录一条数据。</p>
<p>django.session 表中有三个字段。</p>
<ul>
<li>session_key：存的是随机字符串，即响应给浏览器的 cookie 的 sessionid 键对应的值。</li>
<li>session_data：存的是用户的信息，即多个 request.session[“key”]=value，且是密文。</li>
<li>expire_date：存的是该条记录的过期时间（默认14天）</li>
</ul>
</li>
<li><p>d. 浏览器第三次请求其他资源时，携带 cookie :{sessionid:随机字符串}，服务器从 django.session 表中根据该随机字符串取出该用户的数据，供其使用（即保存状态）。</p>
</li>
</ul>
<p><strong>注意:</strong> django.session 表中保存的是浏览器的信息，而不是每一个用户的信息。 因此， 同一浏览器多个用户请求只保存一条记录（后面覆盖前面）,多个浏览器请求才保存多条记录。</p>
<p>cookie 弥补了 http 无状态的不足，让服务器知道来的人是”谁”，但是 cookie 以文本的形式保存在浏览器端，安全性较差，且最大只支持 4096 字节，所以只通过 cookie 识别不同的用户，然后，在对应的 session 里保存私密的信息以及超过 4096 字节的文本。</p>
<p>session 设置：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">request.session[&quot;key&quot;] = value</span><br></pre></td></tr></table></figure>

<p>执行步骤：</p>
<ul>
<li>a. 生成随机字符串</li>
<li>b. 把随机字符串和设置的键值对保存到 django_session 表的 session_key 和 session_data 里</li>
<li>c. 设置 <strong>cookie：set_cookie(“sessionid”,随机字符串)</strong> 响应给浏览器</li>
</ul>
<p>session 获取：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">request.session.get(&apos;key&apos;)</span><br></pre></td></tr></table></figure>

<p>执行步骤：</p>
<ul>
<li>a. 从 cookie 中获取 sessionid 键的值，即随机字符串。</li>
<li>b. 根据随机字符串从 django_session 表过滤出记录。</li>
<li>c. 取出 session_data 字段的数据。</li>
</ul>
<p>session 删除，删除整条记录（包括 session_key、session_data、expire_date 三个字段）：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">request.session.flush()</span><br></pre></td></tr></table></figure>

<p>删除 session_data 里的其中一组键值对：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">del request.session[&quot;key&quot;]</span><br></pre></td></tr></table></figure>

<p>执行步骤：</p>
<ul>
<li>a. 从 cookie 中获取 sessionid 键的值，即随机字符串</li>
<li>b. 根据随机字符串从 django_session 表过滤出记录</li>
<li>c. 删除过滤出来的记录</li>
</ul>
<h5 id="实例"><a href="#实例" class="headerlink" title="实例"></a>实例</h5><p>创建路由:</p>
<p>urls.py</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> session <span class="keyword">import</span> views <span class="keyword">as</span> session_views</span><br><span class="line"></span><br><span class="line">urlpatterns = [</span><br><span class="line">    path(<span class="string">'session_login/'</span>, session_views.login),</span><br><span class="line">    path(<span class="string">'s_index/'</span>, session_views.s_index),</span><br><span class="line">    path(<span class="string">'s_logout/'</span>, session_views.s_logout),</span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<p><img src="https://www.runoob.com/wp-content/uploads/2020/05/Django-cs_8.png" alt="img"></p>
<p>创建视图函数:</p>
<p>Views.py</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">login</span><span class="params">(request)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> request.method == <span class="string">"GET"</span>:</span><br><span class="line">        <span class="keyword">return</span> render(request, <span class="string">"login.html"</span>)</span><br><span class="line">    username = request.POST.get(<span class="string">"username"</span>)</span><br><span class="line">    password = request.POST.get(<span class="string">"pwd"</span>)</span><br><span class="line"></span><br><span class="line">    user_obj = models.UserInfo.objects.filter(username=username, password=password).first()</span><br><span class="line">    print(user_obj.username)</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> user_obj:</span><br><span class="line">        <span class="keyword">return</span> redirect(<span class="string">"/session_login/"</span>)</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        request.session[<span class="string">'is_login'</span>] = <span class="literal">True</span></span><br><span class="line">        request.session[<span class="string">'user1'</span>] = username</span><br><span class="line">        <span class="keyword">return</span> redirect(<span class="string">"/s_index/"</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">s_index</span><span class="params">(request)</span>:</span></span><br><span class="line">    status = request.session.get(<span class="string">'is_login'</span>)</span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> status:</span><br><span class="line">        <span class="keyword">return</span> redirect(<span class="string">'/session_login/'</span>)</span><br><span class="line">    <span class="keyword">return</span> render(request, <span class="string">"s_index.html"</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">s_logout</span><span class="params">(request)</span>:</span></span><br><span class="line">   <span class="comment"># del request.session["is_login"] # 删除session_data里的一组键值对</span></span><br><span class="line">    request.session.flush() <span class="comment"># 删除一条记录包括(session_key session_data expire_date)三个字段</span></span><br><span class="line">    <span class="keyword">return</span> redirect(<span class="string">'/session_login/'</span>)</span><br></pre></td></tr></table></figure>

<p>模板文件：</p>
<p>s_index.html</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE html&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">"en"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"UTF-8"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Title<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">h2</span>&gt;</span>session_index 页面。。。&#123;&#123; request.session.user1 &#125;&#125;<span class="tag">&lt;/<span class="name">h2</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">a</span> <span class="attr">href</span>=<span class="string">"/s_logout/"</span>&gt;</span>注销<span class="tag">&lt;/<span class="name">a</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>
    </div>

  </article>
  <div class="toc-container">
    
  <div id="toc" class="toc-article">
    <strong class="toc-title">目录</strong>
    <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#Django-cookie-与-session"><span class="toc-text">Django cookie 与 session</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Cookies"><span class="toc-text">Cookies</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Django-中-Cookie-的语法"><span class="toc-text">Django 中 Cookie 的语法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#创建应用和模型"><span class="toc-text">创建应用和模型</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Session-保存在服务端的键值对"><span class="toc-text">Session(保存在服务端的键值对)</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#工作原理"><span class="toc-text">工作原理</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#实例"><span class="toc-text">实例</span></a></li></ol></li></ol></li></ol>
  </div>


  </div>
</div>
<script type="text/javascript" src="//rf.revolvermaps.com/0/0/8.js?i=5sr5du46f27&amp;m=0&amp;c=ff0000&amp;cr1=ffffff&amp;f=arial&amp;l=33" async="async"></script>
<div class="copyright">
    <span>本作品采用</span>
    <a href="https://creativecommons.org/licenses/by/4.0/">知识共享署名 4.0 国际许可协议</a>
    <span>进行许可。 转载时请注明原文链接。</span>
</div>


  
    <div class="post-nav" style="margin-left:-168px;">
      <div class="post-nav-item post-nav-next">
        
          <span>〈 </span>
          <a href="/2019/10/30/Go语言标准库flag基本使用/" rel="next" title="GO语言之flag的使用">
          GO语言之flag的使用
          </a>
        
      </div>
  
      <div class="post-nav-item post-nav-prev">
          
          <a href="/2019/12/08/iview的介绍/" rel="prev" title="iview-admin的介绍">
            iview-admin的介绍
          </a>
          <span>〉</span>
        
      </div>
    </div>
  


	
	<div style="width:109%; margin-left:-144px" id="lv-container" data-id="city" data-uid="MTAyMC80OTg5NS8yNjM4Ng==">
	<script type="text/javascript">
   	   (function(d, s) {
       		var j, e = d.getElementsByTagName(s)[0];

       		if (typeof LivereTower === 'function') { return; }

       		j = d.createElement(s);
       		j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
       		j.async = true;

       		e.parentNode.insertBefore(j, e);
   	   })(document, 'script');
	</script>
	<noscript> 为正常使用来必力评论功能请激活JavaScript</noscript>
        </div>
	



    </div>

    

  </div>
  <footer class="footer text-center">
    <div id="bottom-inner">
        <a class="bottom-item" href target="_blank">GitHub</a> |
        <a class="bottom-item" href>友情链接</a> |
        <a class="bottom-item" href="https://hexo.io" target="_blank">Powered by hexo</a> |
        <a class="bottom-item" href="https://github.com/fooying/hexo-theme-xoxo-plus" target="_blank">Theme xoxo-plus</a> |
        <a class="bottom-item" href="/atom.xml">订阅</a>
    </div>
</footer>

  

<script>
  (function(window, document, undefined) {

    var timer = null;

    function returnTop() {
      cancelAnimationFrame(timer);
      timer = requestAnimationFrame(function fn() {
        var oTop = document.body.scrollTop || document.documentElement.scrollTop;
        if (oTop > 0) {
          document.body.scrollTop = document.documentElement.scrollTop = oTop - 50;
          timer = requestAnimationFrame(fn);
        } else {
          cancelAnimationFrame(timer);
        }
      });
    }

    var hearts = [];
    window.requestAnimationFrame = (function() {
      return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback) {
          setTimeout(callback, 1000 / 60);
        }
    })();
    init();

    function init() {
      css(".heart{z-index:9999;width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: absolute;}.heart:after{top: -5px;}.heart:before{left: -5px;}");
      attachEvent();
      gameloop();
      addMenuEvent();
    }

    function gameloop() {
      for (var i = 0; i < hearts.length; i++) {
        if (hearts[i].alpha <= 0) {
          document.body.removeChild(hearts[i].el);
          hearts.splice(i, 1);
          continue;
        }
        hearts[i].y--;
        hearts[i].scale += 0.004;
        hearts[i].alpha -= 0.013;
        hearts[i].el.style.cssText = "left:" + hearts[i].x + "px;top:" + hearts[i].y + "px;opacity:" + hearts[i].alpha + ";transform:scale(" + hearts[i].scale + "," + hearts[i].scale + ") rotate(45deg);background:" + hearts[i].color;
      }
      requestAnimationFrame(gameloop);
    }

    /**
     * 给logo设置点击事件
     * 
     * - 回到顶部
     * - 出现爱心
     */
    function attachEvent() {
      var old = typeof window.onclick === "function" && window.onclick;
      var logo = document.getElementById("logo");
      if (logo) {
        logo.onclick = function(event) {
          returnTop();
          old && old();
          createHeart(event);
        }
      }
      
    }

    function createHeart(event) {
      var d = document.createElement("div");
      d.className = "heart";
      hearts.push({
        el: d,
        x: event.clientX - 5,
        y: event.clientY - 5,
        scale: 1,
        alpha: 1,
        color: randomColor()
      });
      document.body.appendChild(d);
    }

    function css(css) {
      var style = document.createElement("style");
      style.type = "text/css";
      try {
        style.appendChild(document.createTextNode(css));
      } catch (ex) {
        style.styleSheet.cssText = css;
      }
      document.getElementsByTagName('head')[0].appendChild(style);
    }

    function randomColor() {
      // return "rgb(" + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + ")";
      return "#F44336";
    }

    function addMenuEvent() {
      var menu = document.getElementById('menu-main-post');
      if (menu) {
        var toc = document.getElementById('toc');
        if (toc) {
          menu.onclick = function() {
            if (toc) {
              if (toc.style.display == 'block') {
                toc.style.display = 'none';
              } else {
                toc.style.display = 'block';
              }
            }
          };
        } else {
          menu.style.display = 'none';
        }
      }
    }

  })(window, document);
</script>

  



  

</body>
</html>
